package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.ITemplateService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;

@Service
public class TemplateServiceImpl implements ITemplateService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApArticleService apArticleService;

    @Override
    @Async
    /**
     * 这个方法的流程大概跟生成article_content差不多，只不过把对象用freemarker渲染成html
     * 到时候直接访问html就可以获取信息
     */
    public void createHtml(ApArticle apArticle, String content) throws Exception {
        //根据配置找到对应的模板
        Template template = configuration.getTemplate("article.ftl");
        JSONArray contentArray = JSON.parseArray(content);
        HashMap<String, Object> root = new HashMap<>();
        root.put("content", contentArray);
        try {
            minIOService.delete(apArticle.getId()+".html");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out);
             InputStreamReader inputStreamReader = new InputStreamReader(System.in);) {
            //把处理结果输出到out输出流
            //上传静态html文件到minio
            String url = minIOService.upload(apArticle.getId() + ".html", new ByteArrayInputStream(outputStreamWriter.toString().getBytes()), "text/html");
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);
        }

    }
}
